package a06_栈与队列;

import java.util.*;

/**
 * <p>
 * a07_前K个高频元素
 * </p>
 *
 * @author flyduck
 * @since 2024-08-14
 */
public class a08_前K个高频元素 {

    public static void main(String[] args) {
        topKFrequent(new int[]{1,1,1,2,2,3}, 2);
    }

    public static int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if(map.containsKey(nums[i])){
                map.put(nums[i],map.get(nums[i]) + 1);
            }else {
                map.put(nums[i], 1);
            }
        }
        PriorityQueue<Map.Entry<Integer,Integer>> priorityQueue = new PriorityQueue<>((entry1,entry2) -> entry1.getValue() - entry2.getValue());
        for(Map.Entry<Integer,Integer> entry : map.entrySet()){
            priorityQueue.add(entry);
            if(priorityQueue.size() > k){
                priorityQueue.poll();
            }
        }

        int[] result = new int[k];
        for (int i = result.length - 1; i >= 0; i--) {
            result[i] = priorityQueue.poll().getKey();
        }
        return result;
    }
}
